import UseSqliteFun from '@/uni_modules/mc-ui/components/m-sqlite/js_sdk/sqlite-use.js';
import DB from '@/uni_modules/mc-ui/components/m-sqlite/js_sdk/sqlite.js';

const UseSqliteFunByMsg = function() {
	return {
		initSQLite(session_id, successcallback, failcallback) {
			UseSqliteFun.openSQL(ret => {

				// 查一遍是否存在message_unread_records表
				DB.selectTableData('message_unread_records', 'session_id', session_id)
					.then(res => {
						if (!res.length) {
							UseSqliteFunByMsg.insertByNullArr(session_id)
							successcallback && successcallback(res)
						} else {
							// 这里后面需要获取以下content的数量，用作显示未读数量
							successcallback && successcallback(res)
						}
					}, err => {
						UseSqliteFunByMsg.insertByNullArr(session_id, successcallback, failcallback)
						console.log(err);
						successcallback && successcallback(err)
					})
					.catch(error => {
						console.log("查询失败", error);
						failcallback && failcallback(error)
					})
			})

		},
		insertByNullArr(session_id, successcallback, failcallback) {
			let sql =
				'"id" INTEGER PRIMARY KEY AUTOINCREMENT,"session_id" text,"content" text,"lastData" text';

			let param = {
				dbTable: 'message_unread_records',
				sql: sql,
			}
			UseSqliteFun.creatSqlRow(param, function(ret) {
				console.log(ret);
				let time = uni.$m.utils.dateFormat(new Date(), 'Y-MM-dd hh:mm:ss');
				let sql =
					`'${session_id}','${null}','${time}'`;
				let condition = "'session_id','content','lastData'";
				let param = {
					dbTable: 'message_unread_records',
					sql: sql,
					condition: condition,
				};
				console.log(param);
				UseSqliteFun.insertSqlRow(param, function(res) {
					console.log("新增数据成功");
					successcallback && successcallback(res)

				}, function(error) {
					console.log("失败", error);
					failcallback && failcallback(error)
				});
			}, function(err) {
				console.log(err);
				failcallback && failcallback(err)

			});
		},
		updateSqlRow(session_id, sql) {
			let param = {
				dbTable: 'message_unread_records',
				data: sql,
				lname: "session_id",
				lvalue: session_id
			}
			UseSqliteFun.updateSqlRow(param, function() {
				// console.log("新增数据成功");

			}, function(error) {
				console.log("失败", error);
			});
		}
	}
}()

export default UseSqliteFunByMsg;